package com.ifonly.render.renders;

import com.ifonly.common.ContentTypeMapping;
import com.ifonly.render.Render;
import com.ifonly.render.RenderException;
import com.ifonly.utils.JsonUtils;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-10 22:37
 * @since JDK 1.6
 */
public class JsonRender extends Render {

    public Object object;

    public JsonRender(Object object) {
        this.object = object;
    }

    @Override
    public void render() {
        PrintWriter out = null;
        try {
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            String contentType = ContentTypeMapping.APPLICATION_JSON.contentType +
                    CHARSET_PROP +
                    config.getEncoding();

            response.setContentType(contentType);
            String jsonString = JsonUtils.toJson(object, 15);
            out = response.getWriter();
            out.println(jsonString);
            out.flush();
        } catch (IOException e) {
            throw new RenderException(e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
